var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// 在这里去引入你的路由文件
var messageRouter = require('./routes/message');
var zjmRouter = require('./routes/message/zjm')
var jsbRouter = require('./routes/message/jsb')
var ShopfrontRouter=require('./routes/shopfront/index')

var app = express();
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload',express.static(path.join(__dirname, 'upload')));

app.use('/', indexRouter);
// app.use('/users', usersRouter);
// 在这里编写自己的路由
// app.use('/名字',上面定义的名字)q
// app.use('/message', messageRouter)

app.use('/shopfront',ShopfrontRouter)
// app.use('/名字',上面定义的名字)
app.use('/message', messageRouter)
app.use('/zjm', zjmRouter)
app.use("/jsb",jsbRouter)
// 搭建socket.io服务器
const { createServer } = require('http')
const httpServer = createServer(app)
const io = require('socket.io')(httpServer, {
  cors: {
    origin: '*',
  }
})

var { messageModel } = require('./model/model')
io.on('connection', (socket) => {
  socket.on('message', (data) => {
    messageModel.create(JSON.parse(data))
    socket.broadcast.emit('message', JSON.parse(data))
  })
  socket.on('disconnect', () => {
    console.log('断开连接')
  })
})

httpServer.listen(4000, () => {
  console.log('socket.io服务器启动成功')
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
